import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AppComponent } from 'src/app/app.component';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;
  loading = false;
  submitted = false;
  passwordVisible: boolean = false;
  constructor(
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {
    this.validateForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
    });
  }

  get f() {
    return this.validateForm.controls;
  }

  onSubmit() {
    this.submitted = true;

    // reset alerts on submit
    // stop here if form is invalid
    if (this.validateForm.invalid) {
      return;
    }

    this.loading = true;
    let loginValue = this.validateForm.value;
    console.log(loginValue);
    this.http
      .post(
        'http://localhost:8091/api/authenticate',
        loginValue
      )
      .subscribe((res: any) => {
        console.log(res);
        sessionStorage.setItem("token",res.token)
        sessionStorage.setItem("username",loginValue.username)
        window.location.href = '/'
      },

      (error)=>{
        console.log(error)
        this.message.error("用户名或密码错误！")
      });
  }
}
